package be.jabapage.snooker.gui;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import org.apache.commons.lang.Validate;

import be.jabapage.snooker.container.RegionClubContainer;
import be.jabapage.snooker.exception.ProcessingException;
import be.jabapage.snooker.service.importation.api.IRegionImportService;
import be.jabapage.util.MemoryByteArrayOutputStream;

import com.vaadin.ui.Upload.FailedEvent;
import com.vaadin.ui.Upload.FailedListener;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Upload.SucceededListener;

public class ExcelReceiver implements Receiver, SucceededListener, FailedListener, Serializable {
	
	public ExcelReceiver(final IRegionImportService regionImportService) {
		Validate.notNull(regionImportService);
		this.regionImportService = regionImportService;
	}
	private final IRegionImportService regionImportService;

	private ArrayList<Byte> excelFile;
	

	private static final long serialVersionUID = 738017216068371535L;

	public OutputStream receiveUpload(final String filename, final String mimeType) {
		excelFile = new ArrayList<Byte>();
		MemoryByteArrayOutputStream os = new MemoryByteArrayOutputStream(excelFile);
		return os;
	}

	public void uploadFailed(final FailedEvent event) {
		// TODO Auto-generated method stub
	}

	public void uploadSucceeded(final SucceededEvent event) {
		byte [] byteArray = new byte[excelFile.size()];
		int i = 0;
		for (Byte byteElement : excelFile) {
			byteArray[i++] = byteElement;
		}
		ByteArrayInputStream is = new ByteArrayInputStream(byteArray);
		
		try {
			ObjectInputStream oIs = new ObjectInputStream(is);
			RegionClubContainer container = (RegionClubContainer) oIs.readObject();
			
			regionImportService.importClubs(container);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
